import requests
from bs4 import BeautifulSoup
import schedule
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from flask import Flask

# 创建一个简单的HTTP服务器
app = Flask(__name__)

# 目标网站和关键词
TARGET_URL = "URL"
KEYWORD = "example"

# 邮件通知设置
EMAIL_ADDRESS = "your_email@example.com"  # 替换为你的邮箱地址
EMAIL_PASSWORD = "SMTP"  # 替换为你的邮箱密码
RECIPIENT_ADDRESS = "your_email@example.com"  # 替换为接收通知的邮箱地址
SMTP_SERVER = "smtp.qq.com"          # QQ邮箱的SMTP服务器地址
SMTP_PORT = 587                     # QQ邮箱的SMTP端口号

# 检测网页内容是否包含关键词
def check_website():
    try:
        # 获取网页内容
        response = requests.get(TARGET_URL)
        response.raise_for_status()  # 检查请求是否成功
        soup = BeautifulSoup(response.text, 'html.parser')

        # 检查网页内容是否包含关键词
        if KEYWORD in soup.get_text():
            send_email()  # 如果包含关键词，发送邮件通知
            print("检测到关键词，已发送通知邮件！")
        else:
            print("未检测到关键词。")
    except Exception as e:
        print(f"检测过程中发生错误：{e}")

# 发送邮件通知
def send_email(subject="网站内容更新提醒", body=None):
    if body is None:
        body = f"检测到网站 {TARGET_URL} 中出现了关键词：{KEYWORD}"
    msg = MIMEMultipart()
    msg['From'] = EMAIL_ADDRESS
    msg['To'] = RECIPIENT_ADDRESS
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    try:
        server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        server.starttls()
        server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
        server.sendmail(EMAIL_ADDRESS, RECIPIENT_ADDRESS, msg.as_string())
        server.quit()
        print("邮件已发送！")
    except Exception as e:
        print(f"发送邮件时发生错误：{e}")

# 定时任务
def job():
    print("正在检查网页内容...")
    check_website()

# 启动定时任务
@app.before_first_request
def start_scheduler():
    schedule.every(10).minutes.do(job)
    while True:
        schedule.run_pending()
        time.sleep(1)

# 创建一个简单的HTTP接口，用于健康检查
@app.route('/')
def health_check():
    return "服务正常运行！"

if __name__ == "__main__":
    # 发送测试邮件
    send_email(subject="测试邮件", body="这是一封测试邮件，用于确认邮件功能正常。")
    print("已发送测试邮件。")

    # 启动Flask应用，监听端口80
    app.run(host='0.0.0.0', port=80)